package com.weixin.gong.utils.http;

import com.weixin.gong.utils.NullUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.text.MessageFormat;
import java.util.Map;

/**
 * 使用代理的Http工具类
 * @author weixin.gong
 * @date 15-11-10 下午4:53
 */
public class ProxyHttpUtils {
    private static final Logger LOGGER = LoggerFactory.getLogger(ProxyHttpUtils.class);
    private static final int connectTimeout = 100000;
    private static final int requestTimeout = 100000;
    private static final int socketTimeout = 150000;
    private static final HttpClient httpClient;

    static {
        HttpHost proxy = new HttpHost("qproxy.beta.corp.qunar.com", 80);
        RequestConfig defaultRequestConfig = RequestConfig.custom().setConnectionRequestTimeout(requestTimeout)
                .setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).setExpectContinueEnabled(false)
                .setProxy(proxy).build();
        httpClient = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig)
                .setMaxConnTotal(200).build();
    }

    public static String sendGet(String url) throws IOException {
        return send(new HttpGet(url));
    }

    public static String sendGet(String url, Map<String, String> header) throws IOException {
        HttpGet request = new HttpGet(url);
        header = NullUtil.nullToEmpty(header);
        for (Map.Entry<String, String> entry : header.entrySet()) {
            request.setHeader(entry.getKey(), entry.getValue());
        }
        return send(request);
    }

    private static String send(HttpGet request) throws IOException {
        long start = System.currentTimeMillis();
        try {
            request.addHeader("QProxy-Token", "token");
            request.addHeader("qttl", String.valueOf(requestTimeout));
            request.addHeader("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) " +
                    "AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4");
            HttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            String result = EntityUtils.toString(entity, "UTF-8");
            LOGGER.info("method:get, time:{}, req:{}, result:{}", System.currentTimeMillis() - start,
                    request.getURI(), result);
            return result;
        } catch (IOException e) {
            throw new IOException(MessageFormat.format("method:get, time:{0}, req:{1}",
                    System.currentTimeMillis() - start, request.getURI()), e);
        }
    }

}

